package research.ui.editors.tableeditors;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.swt.widgets.TableItem;

import research.entity.Entity;

public abstract class EntityCellModifier implements ICellModifier {
	protected EntityTableEditor viewer;

	public EntityCellModifier(EntityTableEditor viewer) {
		super();
		this.viewer = viewer;
	}

	@Override
	public boolean canModify(Object element, String property) {
		return true;
	}
	
	protected int getColumnIndex(String property) {
		return viewer.getColumnNames().indexOf(property);
	}

	@Override
	public Object getValue(Object element, String property) {
		return getValue((Entity) element, viewer.getColumnNames().indexOf(property));
	}
	
	protected abstract Object getValue(Entity entity, int columnIndex);
	
	protected static int parseInt(Object value) {
		String valueString = ((String) value).trim();
		int i = 0;
		try {
			i = Integer.parseInt(valueString);
		} catch (NumberFormatException e) {
			i = 0;
		}
		return i;
	}
	
	protected static double parseDouble(Object value, double fault) {
		String valueString = ((String) value).trim();
		double d = 0;
		try {
			d = Double.parseDouble(valueString);
		} catch (NumberFormatException e) {
			d = fault;
		}
		return d;
	}
	
	protected static double parseDouble(Object value) {
		return parseDouble(value, 0.0);
	}
	
	protected static String parseString(Object value) {
		String valueString = ((String) value).trim();
		return valueString;
	}

	@Override
	public void modify(Object element, String property, Object value) {
		if (element == null)
			return;

		TableItem item = (TableItem) element;
		if (item == null)
			return;
		
		Entity par = (Entity) item.getData();
		if (par == null)
			return;
		
		modify(par, viewer.getColumnNames().indexOf(property), value);
		
		viewer.getEntityList().valueChanged(par);
//		viewer.refresh();
	}
	
	protected abstract void modify(Entity entity, int columnIndex, Object value);
}
